package lincen.javase.util.string;

import java.util.Arrays;
import java.util.List;

/**
 * 字符串工具
 * @author 	林岑
 * @time	2012年3月23日 14:49:03
 */
public class StringUtil {
	
	/**
	 * 
	 * 将以逗号分隔的字符串equipments的第index个值修改为 value<br>
	 * <br>
	 * 例如: 456564,649871,69871,6464,645  index = 3, value = xxxxxx时, 修改后就得到  456564,649871,69871,xxxxxx,645<br>
	 *  <br>
	 *  如果传入的字符穿当中包含了-1, 那么就自动将-1置为空<br>
	 *  例如: "-1, 123, -1"  alter 1, "xx" ----> ",xx,"
	 * @param equipments	待修改的字符串
	 * @param index			修改第index个逗号 和 index + 1 个逗号所夹的字符串
	 * @param value			修改值
	 */
	public static String alter(String equipments, int index, String value) {

		equipments = equipments.replaceAll(",,", ",-1,");
		equipments = equipments.replace(" ", "");//消除字符串中所有空格
		if(equipments.endsWith(",")) {
			equipments = equipments + "-1";
		}
		if(equipments.startsWith(",")) {
			equipments = "-1" + equipments;
		}


		String[] equips = equipments.split(",");

		equips[index] = value;

		StringBuffer stringLink = new StringBuffer("");
		stringLink.append(equips[0].equals("-1") ? "" : equips[0]);
		for (int i = 1; i < equips.length; i++) {
			stringLink.append("," + (equips[i].equals("-1") ? "" : equips[i]));
		}

		return stringLink.toString();
	}
	

	/*
	 * 读取字符串, 从data的第i个字节开始读取length个长度
	 */
	public static final String subString(byte[] data, int i, int length) {
		return new String(Arrays.copyOfRange(data, i, length + i));
	}
	/**
	 * 将ID列表转成字符串形式, 以逗号分隔
	 * @param idList
	 * @return
	 */
	public static String toStringSplitByComma(List<Integer> idList) {
		if(idList == null || idList.size() == 0) {
			return "";
		}
		String temp = "";
		for (int i = 0; i < idList.size(); i++) {
			Integer id = idList.get( i );
			if(i == 0) {
				temp += id;
			} else {
				temp += "," + id;
			}
		}
		return temp;
	}
}
